<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // 100个请求，如何在最短时间内，获取到这些请求的最短的响应时间的请求
    function getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    const allRequest = new Array(10).fill(0).map((v, index) => () => new Promise(resolve => {
      const times = getRandomInt(1, 10) * 1000
      setTimeout(() => {
        resolve({times, index})
      }, times);
    }))
    console.log(allRequest)
    function getMin(requests) {
      return new Promise(resolve => {
        const COUNT = 2; // 队列数
        let i = 0; // 当前第几次执行
        let minRequest = null; // 当前最短的时间
        function execture() {
          if(i >= requests.length) {
            return resolve(minRequest)
          }
          const end = minRequest ? i + COUNT - 1 : i + COUNT
          const execRequests = requests.slice(i, end)
          if(minRequest) {
            execRequests.push(() => {
              return new Promise(resolve => {
                setTimeout(() => {
                  resolve(minRequest)
                }, minRequest.times);
              })
            })
          }
          const openRequests = execRequests.map(request => request())
          console.log('openRequests',openRequests, i, end)
          return Promise.race(openRequests).then(res => {
            console.log(res)
            minRequest = res
            i = end
            return execture()
          })
        }
        execture()
      })
    }
    getMin(allRequest).then(request => {
      console.log(request)
    })
  </script>
</body>
</html>